<template>
  <div class="tableSelection">
    <h3>table表格跨页多选</h3>
    <br />
    <el-table
      ref="table"
      :data="dataList"
      highlight-selection-row
      tooltip-effect="dark"
      style="width: 100%"
      @row-click="rowClick"
      @selection-change="selectionChange"
    >
      <el-table-column type="selection" align="center" width="100">
      </el-table-column>
      <el-table-column label="日期">
        <template slot-scope="scope">{{ scope.row.date }}</template>
      </el-table-column>
      <el-table-column prop="name" label="姓名"> </el-table-column>
    </el-table>
    <el-pagination
      class="pagination"
      @current-change="handleCurrentChange"
      :current-page.sync="currentPage"
      background
      :page-size="pageSize"
      layout="total,prev, pager, next, jumper"
      :total="tableData.length"
    />
  </div>
</template>
<script>
export default {
  name: 'tableSelection',
  data() {
    return {
      currentPage: 1,
      pageSize: 10,
      selectedRows: [],
      dataList: [],
    }
  },
  computed: {
    tableData() {
      return Array.from({ length: 1000 }, (_, index) => {
        return {
          date: '2016-05-03',
          id: index,
          name: '王小虎' + index,
        }
      })
    },
  },
  mounted() {
    this.fetchData()
  },
  methods: {
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    // 列点击
    rowClick(row) {
      row.selected = !row.selected
      this.$refs.table.toggleRowSelection(row, row.selected)
    },
    // 复选框选中
    selectionChange(selection) {
      this.dataList.forEach((row) => {
        const selected = selection.some((s) => s.id === row.id)
        const selectedRowIndex = this.selectedRows.indexOf(row.id)
        if (selected && selectedRowIndex === -1) {
          this.selectedRows.push(row.id)
        } else if (!selected && selectedRowIndex !== -1) {
          this.selectedRows.splice(selectedRowIndex, 1)
        }
      })
    },
    fetchData() {
      const { tableData, pageSize, currentPage } = this
      const list = tableData.slice(
        (currentPage - 1) * pageSize,
        currentPage * pageSize
      )
      list.forEach((d) => (d.selected = this.selectedRows.includes(d.id)))
      let _index = 0
      list.forEach((d) => {
        d._index = _index++
      })
      this.dataList = list
      this.$nextTick(() => {
        this.dataList
          .filter((v) => v.selected)
          .forEach((d) => this.$refs.table.toggleRowSelection(d, true))
      })
    },
  },
}
</script>
<style lang="less" scoped>
.pagination {
  text-align: center;
  margin-top: 20px;
}
</style>
